# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
from optparse import OptionParser

from cve_ease.notifier import Feishu

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_feishu(gconfig, db_session, args):
    """[notifier] Notifier of feishu"""
    usage = "usage: %prog feishu <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-t', '--test', dest='test', action='store_true', default=False,
                      help='run test')
    parser.add_option('-l', '--list', dest='list', action='store_true', default=False,
                      help='list enable/available key for feishu notifier')
    parser.add_option('-c', '--content', dest='content', default=None,
                      help='test feishu notifier with specific content')

    (options, args) = parser.parse_args(args)

    if options.list:
        from cve_ease.helper import get_wanip, get_watcher, get_timestamp
        watchers = get_watcher(gconfig)
        notifier_name = "feishu_notifier"
        flag = False
        for w in watchers:
            cw = watchers[w]
            if notifier_name not in cw:
                continue
            for key in cw[notifier_name]:
                flag = True
                print(f"key: [ {key} ] for {notifier_name} watcher: {w}")
        if not flag:
            print(f" no avaiable/enabled key for {notifier_name}")
    elif options.test:
        from cve_ease.helper import get_wanip, get_watcher, get_timestamp
        watchers = get_watcher(gconfig)
        notifier_name = "feishu_notifier"
        for w in watchers:
            cw = watchers[w]
            if notifier_name not in cw:
                continue

            description = ''
            if 'description' in cw:
                description = f"功能描述:\n {cw['description']}"

            for key in cw[notifier_name]:
                msg = f"Msg from CVE-EASE: \n" \
                      f"发布时间: {get_timestamp()}\n" \
                      f"{notifier_name}测试\n" \
                      f"IP: {get_wanip()}\n" \
                      f"Watcher: {w}\n" \
                      f"{description}"
                if options.content:
                    msg += f"\n附加信息:\n" \
                           f"{options.content}"
                    notifier = Feishu(gconfig)
                    notifier.send_text(msg, key=key)
                else:
                    notifier = Feishu(gconfig)
                    notifier.send_text(msg, key=key)
                print(f"watcher {w} {notifier_name} send done!")
    else:
        parser.print_help()
